/**
 * Copyright (c) 2017-2018,Retire 吴益峰 (372310383@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.jplus.admin.service.impl;

import com.google.inject.Singleton;
import com.jfinal.kit.Ret;
import io.jboot.aop.annotation.Bean;
import io.jboot.core.rpc.annotation.JbootrpcService;
import io.jplus.admin.model.Menu;
import io.jplus.admin.model.Role;
import io.jplus.admin.model.User;
import io.jplus.admin.service.MenuService;
import io.jplus.admin.service.RoleService;
import io.jplus.admin.service.UserService;
import io.jplus.core.plugin.shiro.ShiroService;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.subject.PrincipalCollection;

import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;

@Bean
@Singleton
@JbootrpcService
public class ShiroServiceImpl implements ShiroService {
    @Inject
    UserService userService;
    @Inject
    RoleService roleService;
    @Inject
    MenuService menuService;


    @Override
    public AuthorizationInfo buildAuthorizationInfo(PrincipalCollection principals) {
        String account = (String) principals.fromRealm("myRealm").iterator().next();
        User user = userService.findByAccount(account);

        List<Role> roles = roleService.findByUserId(user.getId());
        List<Menu> menus = menuService.findByUserId(user.getId());
        List<String> roleList = new ArrayList<>();
        List<String> resList = new ArrayList<>();
        for (Role role : roles) {
            roleList.add(role.getName());
        }
        for (Menu menu : menus) {
            resList.add(menu.getCode());
        }
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        if(roles!=null){
            authorizationInfo.addRoles(roleList);
        }
        if( resList.size()>0) {
            authorizationInfo.addStringPermissions(resList);
        }
        return authorizationInfo;
    }

    @Override
    public Ret shiroLogin(String account, String password) {
        return userService.doLogin(account,password);
    }
}
